﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ProceduralGolf.generation.texture_effects
{
    class TextureScaler : TextureEffect
    {
        private GraphicsDevice graphics;
       
        public TextureScaler(Game game)
        {
            this.graphics = game.GraphicsDevice;
            spriteBatch = new SpriteBatch(graphics);
        }


        public Texture2D scale(Texture2D tex, float scale)
        {
            GraphicsMutex.GetMutex().WaitOne();

            Texture2D result;
            RenderTarget2D target = new RenderTarget2D(graphics, (int)(tex.Width * scale), (int)(tex.Height * scale), 1, graphics.PresentationParameters.BackBufferFormat);
            DepthStencilBuffer stencilBuffer = new DepthStencilBuffer(graphics, (int)(tex.Width * scale), (int)(tex.Height * scale), graphics.DepthStencilBuffer.Format);
            DepthStencilBuffer oldBuffer = graphics.DepthStencilBuffer;

            graphics.DepthStencilBuffer = stencilBuffer;
            graphics.SetRenderTarget(0, target);
            graphics.Clear(Color.TransparentBlack);

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
            spriteBatch.Draw(tex, Vector2.Zero, null, Color.White, 0, Vector2.Zero, scale, SpriteEffects.None, 1);
            spriteBatch.End();

            graphics.SetRenderTarget(0, null);
            graphics.DepthStencilBuffer = oldBuffer;

            result = target.GetTexture();
            stencilBuffer.Dispose();
            target.Dispose();

            GraphicsMutex.GetMutex().ReleaseMutex();

            return result;

        }
    }
}
